#include "screen.h"
#include "io.h"

int global_line;
int global_column;


void getCursorPos(int *line, int *column)
{
	*line = global_line;
	*column = global_column;
}

void setCursorPos(int line, int column)
{

	unsigned short position;
	unsigned char positionLow;
	unsigned char positionHigh;
	
	if(line > 25)
		line = 0;
	
	if(column > 80)
		column = 0;
	
	position = ((line)*80) + column;
	positionLow = 0x0F & position;
	positionHigh = 0x0F & (position >> 4);
	
	// Set cursor position
	outp(0x3d4, 0x0f);
	outp(0x3d5, positionHigh);
	outp(0x3d4, 0x10);
	outp(0x3d5, positionLow);
	
	global_line = line;
	global_column = column;

}

void cls()
{
	int i;
	int total;
	
	total = (80 * 25 * 2)-1;
	
	for(i = 0; i < total; i+=2)
	{
		*(video+i) = 0x20;
		*(video+i+1) = 0x0;

	}
	
	setCursorPos(3, 3);
	
}

void printch(char ch)
{
	int line;
	int column;

	getCursorPos(&line, &column);
	
	if(ch == '\n')
	{
		setCursorPos(++line, 0);
	}
	else
	{
		video = (unsigned char *)(0xb8000 + (line*80*2)+column);
	
		*video = ch;
		video++;
		setCursorPos(line, ++column);
		*video = 0x0f;
		video++;
		setCursorPos(line, ++column);
	}
}

void print(char *str)
{
	unsigned int i;
	unsigned int len;
	
	len = strlen(str);
	
	for(i = 0; i < len; i++)
	{
		printch(*(str+i));
	}

}

void println(char *str)
{
	unsigned int i;
	unsigned int len;
	
	len = strlen(str);
	
	for(i = 0; i < len; i++)
	{
		printch(*(str+i));
	}
	
	printch('\n');
}

unsigned int strlen(char *str)
{
	unsigned int i = 0;
	
	while(*(str+i) != '\0') i++;
	
	return i;
}

/**
 * This function initializes the video device
 * It clears the screen and sets the cursor position to 0,0
 */	
void initScreen()
{
	video = (unsigned char *)0xb8000;
	global_line = 0;
	global_column = 0;
	cls();
}
